import os
import time
import sqlite3
import datetime

class justMatched:
    dbFile = '/tmp/stn.sqlite'
    tableName = 'just_matched'
    cursor = connection = None
    
    def __init__(self, dbFile=None):
        # if not set (dbFile) set default
        self.dbFile = (dbFile if (dbFile is not None) else self.dbFile)
        self.dbFile = os.path.abspath(self.dbFile)
        self.connection = sqlite3.connect(self.dbFile)
        self.cursor = self.connection.cursor()
    
    def createTable(self):
        # Drop table
        self.cursor.execute("DROP TABLE IF EXISTS %s" % self.tableName)
        
        # Create table
        self.cursor.execute('''CREATE TABLE %s 
                    (id INTEGER PRIMARY KEY,
                     match TEXT NOT NULL, 
                     scope TEXT DEFAULT NULL, 
                     time INTEGER)''' % self.tableName)
        self.cursor.execute("CREATE INDEX match_scope ON %s (match, scope, time)" % self.tableName);
        
        self.connection.commit()
        
    # check if there is just the matched record with gaptime respected...if not insert it
    # true: just mathced in the past (gapTime)
    # false: not just matched or to old (gapTime not respected)
    def check(self, match, gapTime=None, scope=None):
        sql = "SELECT * FROM %s WHERE match = '%s'" % (self.tableName, match)
        
        if(gapTime is not None or gapTime is '-1'):
            timeLessGapTime = datetime.datetime.now() - datetime.timedelta(seconds=gapTime)
            sql += " AND time >= '%s'" % time.mktime(timeLessGapTime.timetuple())
        
        if(scope is not None):
            sql += " AND scope = '%s'" % scope
        
        self.cursor.execute(sql)
        
        if(len(self.cursor.fetchall())):
            return True
        else:
            # insert with now() as time
            self.__insert(match, scope=scope)
            return False
        
    def __insert(self, match, timestamp=None, scope=None):
        scope = ('NULL' if(scope is None) else "'%s'" % scope)
        # set timestamp to now() if None
        timestamp = (time.mktime(datetime.datetime.now().timetuple()) if(timestamp is None) else timestamp)
        
        self.cursor.execute("INSERT INTO %s VALUES (NULL, '%s', %s, '%s')" % (self.tableName, match, scope, timestamp))
        self.connection.commit()
        
    def __del__(self):
        self.connection.close()